// vue3 封装分页请求hook
import { ref, reactive, onMounted, onUnmounted } from 'vue'
export default function usePageRequest(getListFunc, params) {
    const page = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const list = ref([])
    const loading = ref(false)
    const error = ref(false)
    const handlePageChange = (val) => {
        page.value = val
        getList()
    }
    const handlePageSizeChange = (val) => {
        pageSize.value = val
        getList()
    }
    const handleSearch = () => {
        page.value = 1
        getList()
    }
    const handleReset = () => {
        page.value = 1
        pageSize.value = 10
        getList()
    }
    const nextPage = () => {
        if (page.value * pageSize.value < total.value) {
            page.value++
            getList()
        }
    }
    const prevPage = () => {
        if (page.value > 1) {
            page.value--
            getList()
        }
    }
    // const handleScroll = () => {
    //     if (loading.value || error.value) return
    //     const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
    //     const windowHeight = document.documentElement.clientHeight || document.body.clientHeight
    //     const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
    //     if (scrollTop + windowHeight >= scrollHeight) {
    //         nextPage()
    //     }
    // }
    // onMounted(() => {
    //     window.addEventListener('scroll', handleScroll)
    // })


    const getList = async () => {
        loading.value = true
        try {
            const res = await getListFunc({
                ...params,
                page: page.value,
                pageSize: pageSize.value
            })
            list.value = res.data.list
            total.value = res.data.total
        } catch (e) {
            error.value = true
        }
        loading.value = false
    }
    onMounted(() => {
        getList()
    })
    return {
        page,
        pageSize,
        total,
        list,
        loading,
        error,
        getList,
        handlePageChange,
        handlePageSizeChange,
        handleSearch,
        handleReset,
        nextPage,
        prevPage
    }
}
